<template>
  <div class="app-container">
    <el-container>
      <!-- 顶部导航 -->
      <el-header>
        <div class="header-content">
          <h1>RAG Text2SQL评估系统</h1>
          <span class="subtitle">基于LLM的SQL生成准确率评估工具</span>
        </div>
      </el-header>
      
      <!-- 主要内容区域 -->
      <el-main>
        <el-tabs v-model="activeTab" type="border-card" class="main-tabs">
          <!-- 文本转SQL标签页 -->
          <el-tab-pane label="文本转SQL" name="text2sql">
            <div class="text2sql-container">
              <el-input
                v-model="question"
                type="textarea"
                :rows="4"
                placeholder="请输入您的自然语言问题..."
                class="question-input"
              />
              
              <el-button 
                type="primary" 
                @click="convertToSql"
                :loading="isLoading"
                class="convert-btn"
              >
                生成SQL
              </el-button>
              
              <div v-if="sqlResult" class="result-container">
                <el-divider content-position="left">生成结果</el-divider>
                
                <div class="sql-result">
                  <h3>SQL语句：</h3>
                  <el-input
                    v-model="sqlResult.generated_sql"
                    type="textarea"
                    :rows="6"
                    readonly
                    class="generated-sql"
                  />
                  <div class="confidence-score">
                    置信度：{{ (sqlResult.confidence_score * 100).toFixed(2) }}%
                  </div>
                </div>
                
                <el-divider content-position="left">相关文档</el-divider>
                <div class="context-docs">
                  <el-collapse v-model="activeDocs">
                    <el-collapse-item 
                      v-for="(doc, index) in sqlResult.context_documents" 
                      :key="doc.id"
                      :title="`文档 ${index + 1} (相似度: ${(1 - doc.distance).toFixed(3)})`"
                    >
                      <pre>{{ doc.document }}</pre>
                    </el-collapse-item>
                  </el-collapse>
                </div>
                
                <div class="action-buttons">
                  <el-button 
                    type="success" 
                    @click="evaluateGeneratedSql"
                    class="evaluate-btn"
                  >
                    评估SQL
                  </el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- SQL评估标签页 -->
          <el-tab-pane label="SQL评估" name="evaluation">
            <div class="evaluation-container">
              <el-input
                v-model="evalQuestion"
                type="textarea"
                :rows="2"
                placeholder="请输入问题描述..."
                class="eval-question-input"
              />
              
              <el-input
                v-model="generatedSql"
                type="textarea"
                :rows="4"
                placeholder="请输入生成的SQL语句..."
                class="eval-sql-input"
              />
              
              <el-input
                v-model="expectedSql"
                type="textarea"
                :rows="4"
                placeholder="请输入预期的SQL语句（可选）..."
                class="eval-expected-input"
              />
              
              <el-button 
                type="primary" 
                @click="evaluateSql"
                :loading="isEvaluating"
                class="eval-btn"
              >
                开始评估
              </el-button>
              
              <div v-if="evalResult" class="eval-result-container">
                <el-divider content-position="left">评估结果</el-divider>
                
                <div class="evaluation-summary">
                  <div class="score-display">
                    相似度得分：<span class="score">{{ (evalResult.similarity_score * 100).toFixed(2) }}%</span>
                  </div>
                  <div class="correctness">
                    评估结果：<span :class="['result-badge', evalResult.is_correct ? 'correct' : 'incorrect']">
                      {{ evalResult.is_correct ? '正确' : '不正确' }}
                    </span>
                  </div>
                </div>
                
                <el-divider content-position="left">详细对比</el-divider>
                <div class="comparison-details">
                  <div class="detail-section">
                    <h4>生成的SQL关键字：</h4>
                    <el-tag 
                      v-for="keyword in evalResult.evaluation_details.generated_elements.keywords" 
                      :key="keyword"
                      class="keyword-tag"
                    >
                      {{ keyword }}
                    </el-tag>
                  </div>
                  
                  <div class="detail-section">
                    <h4>生成的表名：</h4>
                    <el-tag 
                      v-for="table in evalResult.evaluation_details.generated_elements.tables" 
                      :key="table"
                      class="table-tag"
                    >
                      {{ table }}
                    </el-tag>
                  </div>
                  
                  <div class="detail-section">
                    <h4>生成的列名：</h4>
                    <el-tag 
                      v-for="column in evalResult.evaluation_details.generated_elements.columns" 
                      :key="column"
                      class="column-tag"
                    >
                      {{ column }}
                    </el-tag>
                  </div>
                  
                  <div v-if="evalResult.evaluation_details.similarity_metrics.structure_match" class="detail-section">
                    <h4>结构匹配度：</h4>
                    <div class="structure-match">
                      {{ (evalResult.evaluation_details.similarity_metrics.structure_match * 100).toFixed(2) }}%
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 数据管理标签页 -->
          <el-tab-pane label="数据管理" name="data">
            <div class="data-container">
              <el-button 
                type="primary" 
                @click="loadQ2SqlPairs"
                :loading="isLoadingData"
                class="load-data-btn"
              >
                加载问题-答案对
              </el-button>
              
              <div v-if="q2sqlPairs.length > 0" class="pairs-container">
                <el-table :data="q2sqlPairs" style="width: 100%">
                  <el-table-column prop="question" label="问题" width="500" />
                  <el-table-column prop="sql" label="SQL语句">
                    <template #default="scope">
                      <el-input :value="scope.row.sql" type="textarea" :rows="2" readonly />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="scope">
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="usePair(scope.row)"
                      >
                        使用
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      
      <!-- 底部信息 -->
      <el-footer>
        <div class="footer-content">
          <p>RAG Text2SQL评估系统 &copy; 2025</p>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'App',
  data() {
    return {
      activeTab: 'text2sql',
      question: '',
      sqlResult: null,
      isLoading: false,
      activeDocs: [],
      
      evalQuestion: '',
      generatedSql: '',
      expectedSql: '',
      evalResult: null,
      isEvaluating: false,
      
      q2sqlPairs: [],
      isLoadingData: false
    }
  },
  methods: {
    // 文本转SQL
    async convertToSql() {
      if (!this.question.trim()) {
        this.$message.warning('请输入问题')
        return
      }
      
      this.isLoading = true
      try {
        const response = await axios.post('/text2sql', {
          question: this.question
        })
        this.sqlResult = response.data
        this.activeDocs = [0] // 默认展开第一个文档
      } catch (error) {
        this.$message.error('生成SQL失败：' + error.message)
        console.error('Text2SQL error:', error)
      } finally {
        this.isLoading = false
      }
    },
    
    // 评估生成的SQL
    evaluateGeneratedSql() {
      if (!this.sqlResult) return
      
      this.activeTab = 'evaluation'
      this.evalQuestion = this.sqlResult.question
      this.generatedSql = this.sqlResult.generated_sql
    },
    
    // 评估SQL
    async evaluateSql() {
      if (!this.generatedSql.trim()) {
        this.$message.warning('请输入要评估的SQL语句')
        return
      }
      
      this.isEvaluating = true
      try {
        const response = await axios.post('/evaluate', {
          question: this.evalQuestion,
          generated_sql: this.generatedSql,
          expected_sql: this.expectedSql || null
        })
        this.evalResult = response.data
      } catch (error) {
        this.$message.error('评估失败：' + error.message)
        console.error('Evaluation error:', error)
      } finally {
        this.isEvaluating = false
      }
    },
    
    // 加载问题-答案对
    async loadQ2SqlPairs() {
      this.isLoadingData = true
      try {
        const response = await axios.get('/q2sql-pairs')
        this.q2sqlPairs = response.data
      } catch (error) {
        this.$message.error('加载数据失败：' + error.message)
        console.error('Load data error:', error)
      } finally {
        this.isLoadingData = false
      }
    },
    
    // 使用问题-答案对
    usePair(pair) {
      this.activeTab = 'text2sql'
      this.question = pair.question
      this.expectedSql = pair.sql
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
}

.subtitle {
  margin-left: 15px;
  font-size: 14px;
  opacity: 0.9;
}

.el-main {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.main-tabs {
  height: 100%;
}

.text2sql-container,
.evaluation-container,
.data-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-input,
.eval-question-input,
.eval-sql-input,
.eval-expected-input {
  margin-bottom: 15px;
}

.convert-btn,
.eval-btn,
.load-data-btn {
  align-self: flex-start;
  margin-bottom: 20px;
}

.result-container,
.eval-result-container {
  flex: 1;
  overflow-y: auto;
}

.sql-result {
  margin-bottom: 20px;
}

.generated-sql {
  font-family: 'Courier New', monospace;
}

.confidence-score {
  margin-top: 10px;
  font-weight: bold;
  color: #409eff;
}

.context-docs {
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 15px;
}

.evaluation-summary {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.score-display .score {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.result-badge {
  padding: 5px 10px;
  border-radius: 5px;
  font-weight: bold;
}

.result-badge.correct {
  background-color: #f0f9ff;
  color: #409eff;
}

.result-badge.incorrect {
  background-color: #fef0f0;
  color: #f56c6c;
}

.comparison-details {
  margin-top: 20px;
}

.detail-section {
  margin-bottom: 15px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.keyword-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  margin-right: 5px;
  margin-bottom: 5px;
}

.table-tag {
  background-color: #f6ffed;
  color: #52c41a;
  margin-right: 5px;
  margin-bottom: 5px;
}

.column-tag {
  background-color: #fff7e6;
  color: #fa8c16;
  margin-right: 5px;
  margin-bottom: 5px;
}

.structure-match {
  font-size: 16px;
  font-weight: bold;
  color: #722ed1;
}

.pairs-container {
  flex: 1;
  overflow-y: auto;
  margin-top: 15px;
}

.el-footer {
  text-align: center;
  padding: 10px 0;
  background-color: #f5f7fa;
  color: #606266;
}

.footer-content p {
  margin: 0;
}
</style>